/*
 * Copyright (c) 2018. wupj
 */

function CompanyComponent(data, defaultPkCorp) {
    this.init();
    this.$el = $('#company-component');
    this.companyList = data; //公司数组
    this.companyModal = {};
    this.defaultCorp = defaultPkCorp; //默认公司编码
    this.currentCompany = {}; //当前公司
    this.currentCompanyTemp = {}; //临时
    this.isCompanyModalClick = false;
    this.renderCompanyModal();
}

CompanyComponent.prototype.init = function() {
    $('body').append('<div id="company-component"></div>')
};
CompanyComponent.prototype.renderCompanyModal = function() {
    var _this = this;
    //每次打开框设置读取本地（让点击取消能回到上次没有编辑前的效果）
    this.currentCompanyTemp = JSON.parse(JSON.stringify(_this.currentCompany || {}));
    var html = '  <div class="company-wrap"><div class="company-modal-title">请选择公司</div>\n' +
        '        <div class="current-company" title="切换公司">\n' +
        '       	 <span class="current-load-company" >当前选择公司：<span><span class="current-company-name" title="' + this.currentCompanyTemp.unitname + '">' + (this.currentCompanyTemp.unitname || "--") + '</span></span>' +
        '        </div>\n' +
        // '        <div class="choice-company">\n' +
        // '            <span class="current-company-label">选择公司：</span><span class="current-company-name" title="' + this.currentCompanyTemp.unitname + '">' + this.currentCompanyTemp.unitname + '</span>\n' +
        // '        </div>\n' +
        '        <ul class="company-list">';
    for (var i = 0; i < this.companyList.length; i++) {
        var isDefault = this.companyList[i].pk_corp == this.defaultCorp;
        html += '            <li class="company-item" data-corp="' + this.companyList[i].pk_corp + '">\n' +
            '                <span class="radio ' + (this.companyList[i].pk_corp == this.currentCompanyTemp.pk_corp ? "active" : "") + '"><i class="fa fa-circle-o"></i></span>\n' +
            '                <span class="company-name" title="' + this.companyList[i].unitname + '">' + this.companyList[i].unitname + '</span>\n' +
            '                <span class="set-default ' + (isDefault ? "active" : "deactived") + '">' +
            // '                   <span class="default-btn" title="设为默认"><i class="fa  fa-check-square-o" ></i>设为默认</span>' +
            '                   <span class="default"  title="默认"><i class="fa fa-square-o" ></i>默认</span>' +
            '               </span>\n' +
            '            </li>\n'
    }
    html += '        </ul>\n' +
        '    </div><div class="modal-footer">' +
        ' <label><input name="company" type="checkbox" onclick="checkboxOnclick(this)" value="" />记住选择 </label>  ' +
        '       <button class="modal-btn btn-text company cancel ' + (this.currentCompany.pk_corp ? 'active' : "") + '">取消</button>' +
        '       <button class="modal-btn btn-primary confirm">确定</button>' +
        '   </div>';
    var modal = '<div class="company-wrap-cas"><div class="company-cas-modal"> ' + html + '</div></div>';
    this.$el.html(modal);

    this.modalHandler();
    //退出模态框关闭/按钮取消
    $(".company-modal .close-icon,.company-modal .modal-btn.cancel").click(function() {
        if (_this.isCompanyModalClick) return;
        _this.closeCropModal();
    });
    //ESC退出按钮
    //确定
    $(".company-cas-modal .modal-btn.confirm").click(function() {
        if (!_this.currentCompanyTemp.pk_corp) {
            yytUtil.msg.showWarnMsg('请选择公司。');
            return;
        }
        $("#pk_corp").val(_this.currentCompanyTemp.pk_corp);
        $("#password").val($("#md5pwd").val());
        $("input[type=submit]").click();
        _this.closeCropModal();
    })
};
CompanyComponent.prototype.closeCropModal = function() {
    if (!this.currentCompanyTemp.pk_corp) {
        yytUtil.msg.showWarnMsg('请选择登录公司。');
        return;
    }
    companyComponent.hideCompanyModal();
};
CompanyComponent.prototype.modalHandler = function() {
    //设置默认
    var _this = this;
    $(".company-wrap").on('click', '.set-default', function(e) {
        e.stopPropagation();
        e.preventDefault();
        if (!$(this).hasClass('active')) {
            var corp = $(this).parent('.company-item').attr('data-corp');
            var $el = $(this);
            if (_this.isCompanyModalClick) return;
            _this.setDefaultCompany(corp, function() {
                yytUtil.msg.showSuccessMsg('设置成功！');
                _this.defaultCorp = corp;
                $el.addClass('active').removeClass('deactived');
                $el.parent('.company-item').siblings().find('.set-default').removeClass('active').addClass('deactived')
            });
        }
    });
    $(".company-wrap").on('click', '.company-item', function(e) {
        var corp = $(this).data('corp');
        var name = $(this).find('.company-name').text();
        $('.choice-company').show();
        $(this).addClass('active');
        $('.current-company-name').text(name);
        $('.current-company-name').attr('title', name);
        $(this).siblings().removeClass('active');
        _this.currentCompanyTemp = {
            unitname: name,
            pk_corp: corp
        };
    })
};

CompanyComponent.prototype.showCompanyModal = function() {
    this.$el.find('.company-wrap-cas').addClass('active');
};
CompanyComponent.prototype.hideCompanyModal = function() {
    this.$el.find('.company-wrap-cas').removeClass('active');
};
var companyComponent = {};

function initCorpData(username, password, verifycode, successFunc, failFunc) {
    var result = false;
    var ele = $(".login-form")[0];
    // yytUtil.msg.showLoading(ele);
    var smsPassword = $("#smsPassword") ? $("#smsPassword").val() : "";
    $.ajax({
        url: 'validUser',
        type: "POST",
        // async: false,
        dataType: "json",
        data: {
            username: username,
            password: password,
            verifycode: verifycode,
            smsPassword: smsPassword,
            csrfToken: $("#csrfToken").val()
        },
        success: function(data) {
            if (data.success == true && data.data) {
                var callback = function() {
                    if (data.errorCode == "-33") {
                        confirmPirvacyPolicy(data.uid);
                        yytUtil.msg.stopLoading(ele);
                        return;
                    }
                    caMsg = data.caMsg;
                    var token = data.token;
                    data = data.data;
                    // add by chenbd 如果已经指定pk_corp，就不用选了
                    // 如果当前有pk_corp参数，登录公司就用这个了
                    if (token) {
                        $('#token').val(token);
                    }
                    var pkcorp = getQueryStringByName("loginpkcorp");
                    if (pkcorp) {
                        $("#pk_corp").val(pkcorp)
                        successFunc(caMsg);
                    } else
                        // 只有一个公司，那么就是这个公司了，不弹窗选择
                        if (data.corps.length == 1) {
                            $("#pk_corp").val(data.corps[0].pk_corp);
                            successFunc(caMsg);
                        } else
                            // 已经有默认公司了，也不用弹窗选择
                            if (data.defaultPkCorp) {
                                $("#pk_corp").val(data.defaultPkCorp);
                                successFunc(caMsg);
                            } else if (data.corps.length == 2) {
                        // 是否包含集团，包含集团不弹窗
                        var corpNo1 = data.corps[0].pk_corp;
                        var corpNo2 = data.corps[1].pk_corp;
                        if (corpNo1 == "0001") {
                            $("#pk_corp").val(corpNo2);
                            successFunc(caMsg);
                        } else if (corpNo2 == "0001") {
                            $("#pk_corp").val(corpNo1);
                            successFunc(caMsg);
                        } else {
                            var result = initCaMsg(caMsg);
                            if (!result) {
                                return false;
                            }
                            companyComponent = new CompanyComponent(data.corps || [], data.defaultPkCorp);
                            companyComponent.showCompanyModal();
                        }
                    } else if (data.corps.length > 2) {
                        var result = initCaMsg(caMsg);
                        if (!result) {
                            return false;
                        }
                        companyComponent = new CompanyComponent(data.corps || [], data.defaultPkCorp);
                        companyComponent.showCompanyModal();
                    } else {
                        failFunc();
                    }
                    yytUtil.msg.stopLoading(ele);
                }
                if (data.errorCode == "-3") {
                    confirmPwd(data.message, data.errorCode).then(function(res) {
                        // 修改密码
                        if (res) {
                            modifyPwd(data);
                            yytUtil.msg.stopLoading(ele);
                        } else {
                            // 下次修改
                            callback();
                        }
                    })
                } else {
                    callback();
                }
            } else {
                if (data.errorCode == "-2") { //修改密码
                    modifyPwd(data);
                } else {
                    //验证码过期，刷新验证码
                    checkVerifyCodeAjax();
                    failFunc(data.message || data.msg || "系统内部异常，稍后再试!");
                }
                yytUtil.msg.stopLoading(ele);
            }
            // 跟前端商定后先注释小这一行,为了解决登录可以多次点击的情况
            //  yytUtil.msg.stopLoading(ele);
        },
        error: function(err) {
            if (403 == err.status) {
                yytUtil.msg.showErrorMsg('页面操作已超时,请刷新页面!');
            } else {
                yytUtil.msg.showErrorMsg("系统内部异常，稍后再试!");
            }
            companyComponent = new CompanyComponent([], "");
            yytUtil.msg.stopLoading(ele);
        }
    });
    return result;
}

function checkboxOnclick(checkbox) {
    if (checkbox.checked == true) {
        $("#defaultPkCorp").val(1);
    } else {
        $("#defaultPkCorp").val(0);
    }
}

function initCaMsg(caMsg) {
    if (caMsg) {
        if ((new RegExp("^-1")).test(caMsg)) {
            //出错
            var arr = caMsg.split("\|");
            yytUtil.msg.showErrorMsg(arr[1])
            $(this).val("登录");
            return false;
        } else if ((new RegExp("^1")).test(caMsg)) {
            //ca登录
            var arr = caMsg.split("\|");
            var dn = arr[1];
            if (arr.length == 4 && arr[3] == 2) {
                // 信安2.0
                var res = doCaLogin2(arr[1], arr[2]);
                if (!res) {
                    return false;
                }
            } else if (dn != null && dn.length > 0) {
                if (document.getElementById("InfoSecNetSign1") == null) {
                    var caDivObj = document.getElementById("caDiv");
                    caDivObj.innerHTML = '<OBJECT id=InfoSecNetSign1 style="WIDTH: 0px; HEIGHT: 0px" data=data:application/x-oleobject;base64,xDi5s5BBN0+M8KkrCpHMdwADAACyHgAA/wIAAA== codebase=NetSignGM.cab#version=1,0,74,1 classid=clsid:4D47B398-BCAA-4b68-B4BE-64EEA9ADDBC4 VIEWASTEXT></OBJECT>'
                }
                var res = doCaLogin(arr[1], arr[2]);
                if (!res) {
                    return false
                }
            }
        }
    }
    return true
}

function confirmPirvacyPolicy(uid) {
    window.top.addEventListener('message', function(e) {
        if (e.data === 'agreePrivacyPolicy') {
            var index = window.privacyModal.options.content.indexOf('uid=') + 4;
            var uid = window.privacyModal.options.content.substring(index);
            $.ajax({
                url: 'signPrivacyPolicy',
                type: "POST",
                dataType: "json",
                data: {
                    uid: uid
                },
                success: function(data) {
                    if (data.success == true && data.data) {
                        data = data.data;
                        var targetUrl = document.URL;
                        if (document.URL.indexOf('?') != -1) {
                            targetUrl += '&';
                        } else {
                            targetUrl += '?';
                        }
                        targetUrl += 'token=' + data.token;
                        location.href = targetUrl;
                    } else {
                        yytUtil.msg.showErrorMsg("隐私协议签订失败");
                    }
                },
                error: function(err) {
                    yytUtil.msg.showErrorMsg("隐私协议签订失败");
                }
            });
            // 关闭弹窗
            window.privacyModal && window.privacyModal.destroy();
        } else if (e.data === 'disagreePrivacyPolicy') {
            // 关闭弹窗
            location.reload();
        }
    });
    window.privacyModal = yytUtil.modal({
        // title: '',
        type: 'iframe',
        content: './privacy-policy?uid=' + uid,
        className: 'iframeModal pageModal',
        width: window.innerWidth * 0.9,
        height: window.innerHeight * 0.8,
        enableClose: false,
        isShowFooter: false,
        uid: uid
    });

}